package com.cj.util;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.stereotype.Component;

@Component
public class RedisLock {
	//加锁
		public boolean addLock(RedisTemplate<String, String> redisTemplate) {
			boolean lock = redisTemplate.execute(new RedisCallback<Boolean>(){
				public Boolean doInRedis(RedisConnection connection) throws DataAccessException{
					String key = "lock";
					String value = "1";
					if(connection.setNX(key.getBytes(), value.getBytes())) {
						redisTemplate.expire(key, 2, TimeUnit.SECONDS);
						return true;
					}else {
						return false;
					}
				}
			});
			return lock;
		}
	
	//加锁
	public boolean addLock(RedisTemplate<String, String> redisTemplate,String uuId) {
		boolean lock = redisTemplate.execute(new RedisCallback<Boolean>(){
			public Boolean doInRedis(RedisConnection connection) throws DataAccessException{
				String key = "lock";
				String value = uuId;
				if(connection.setNX(key.getBytes(), value.getBytes())) {
					redisTemplate.expire(key, 15, TimeUnit.SECONDS);
					return true;
				}else {
					return false;
				}
			}
		});
		return lock;
	}
	
	
	

}
